<?php
namespace app\pay\controller;
use think\Controller;
use think\Request;

use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\ExecutePayment;
use think\Db;
use fast\Random;

class Index extends Controller
{
    //回调
    public function exec(Request $request){
        // # # #批准状态
        //决定用户是否同意支付。
        $clientId = 'AS0Tr_UyrEGR6TTQ48SRBLsGP-3yf7DLJ1a2qbjR_FCsHLHOlakWnuvVTHuty_gjG85u_SFZxKYGKKEB';
        $clientSecret = 'EPPMj0RxcjnFKvN2S9KHec_xT5zEWFmtJfJLnb8tK9EIrnYOGrEMHT04Fo3izghIi1hK5v8wWiVF0-m9';
//        $clientId='AXGZVTjhw2zxUaXMEF2ocxdMrOL2dvaqmZLfbzUgWuH_WNsvveZOHLNml6KDvyCN85G6D3jwku_4n_dY';
//        $clientSecret='EM7T7JmK3R0zOEDTiD8W0Iatew92-2hPuv_m52ofDtxK14hZPixaab4q0z67NhuRq9OaRjSy7wTzu7AA';
        $apiContext = new ApiContext(
            new OAuthTokenCredential(
                $clientId,
                $clientSecret
            )
        );
        $apiContext->setConfig(
            array(
                'mode' => 'live',
                'log.LogEnabled' => true,
                'log.FileName' => '../PayPal.log',
                'log.LogLevel' => 'INFO', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
                'cache.enabled' => true,
                // 'http.CURLOPT_CONNECTTIMEOUT' => 30
                // 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
                //'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
            )
        );
        if($request->isGet()){
            $success=$request->param('success');
            $paymentId=$request->param('paymentId');
            $PayerID=$request->param('PayerID');

            if(!isset($success, $paymentId, $PayerID)){
                die();
            }

            if((bool)$success=== 'false'){

                echo 'Transaction cancelled!';
                die();
            }

            $paymentId = $_GET['paymentId'];
            $payerId = $_GET['PayerID'];

            $payment = Payment::get($paymentId, $apiContext);

            $execute = new PaymentExecution();
            $execute->setPayerId($payerId);

            try{
                $result = $payment->execute($execute, $apiContext);
                echo "<pre>";
                $transactions=$result->transactions;
                $item_list=$transactions[0]->item_list;
                $items=$item_list->items;
                $sku=$items[0]->sku;
                $xtmoney=$items[0]->description;
                $price=$items[0]->price;

                Db::startTrans();    //开启事务
                try{
                    $wallet=Db::table("t_capital")->where("uid",$sku)->value("wallet");
                    $newwallet = $wallet+$xtmoney;
                    Db::table('t_capital')->where('uid',$sku) ->update([
                        'wallet'  => $newwallet
                    ]);
                    $number=Random::numeric(16);
                    $investdata = ['uid' => $sku, 'money' => $xtmoney,'source'=>4,'number'=>$number,'addtime'=>time()];
                    Db::table('t_capital_charge')->insert($investdata);


                    Db::commit();   //提交事务
                }catch(Exception $e){
                    Db::rollback(); //回滚事务
                    return ['code' => 201,"msg"=>$e];
                    die();
                }


            }catch(Exception $e){
                die($e);
            }
            $this->redirect('http://www.91ggjf.cn/Success.html',302);
            die();
        }
    }

    public function cancel(){
        echo '取消支付';
    }
}
